package com.sds.sweng.swat.miplatform.ui.design.models.component;

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.eclipse.ui.views.properties.IPropertyDescriptor;
import org.eclipse.ui.views.properties.PropertyDescriptor;

import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.TableCellSubArea;
import com.sds.sweng.swat.miplatform.ui.design.models.component.logical.LogicalComponent;
import com.sds.sweng.swat.miplatform.ui.design.utils.CloneUtils;

public class MTableComponents extends TableCellSubArea {

	public static final int
		CELL_LEFT_MARGIN = 3,
		CELL_RIGHT_MARGIN = 3,
		CELL_TOP_MARGIN = 2;

	public static final String
		COMPONENTS = "components";

	static {
		descriptors = new IPropertyDescriptor[] {
			new PropertyDescriptor(COMPONENTS, "Components")
		};
	}

	private List<LogicalComponent> components = new ArrayList<LogicalComponent>();

	public MTableComponents() {
		this(0, 0, 0, 1);
	}

	public MTableComponents(int col, int row, int width) {
		this(col, row, width, 1);
	}

	public MTableComponents(int col, int row, int width, int colspan) {
		super(col, row, width, colspan);
	}

	public MTableComponents clone() {
		MTableComponents clone = (MTableComponents) super.clone();
		clone.setComponents(CloneUtils.clone(getComponents()));

		return clone;
	}

	public List<LogicalComponent> getComponents() {
		return components;
	}

	@JsonIgnore
	public int getComponentsWidth() {
		int componentsWidth = CELL_LEFT_MARGIN + CELL_RIGHT_MARGIN;

		for (int i=0;i<components.size();i++) {
			componentsWidth += components.get(i).getWidth();

			if (i < components.size()-1)
				componentsWidth += components.get(i).getRightMargin();
		}

		return componentsWidth;
	}

	public int getRemainWidth() {
		int remainWidth = getWidth();
		remainWidth -= CELL_LEFT_MARGIN + CELL_RIGHT_MARGIN;
		remainWidth -= (isFirstCell() ? 1 : 0) + (isLastCell() ? 1 : 0);

		for (int i=0;i<components.size();i++) {
			LogicalComponent component = (LogicalComponent) components.get(i);

			remainWidth -= component.getWidth();
			remainWidth -= component.getRightMargin();
		}

		return remainWidth;
	}

	public void setComponents(List<LogicalComponent> components) {
		this.components = components;
		firePropertyChange(COMPONENTS, null, components);
	}

	public Object getPropertyValue(Object id) {
		if (COMPONENTS.equals(id))
			return getComponents();

		return null;
	}

	public void setPropertyValue(Object id, Object value) {
		if (COMPONENTS.equals(id))
			setComponents((List<LogicalComponent>) value);
	}

	@Override
	public boolean isEmpty() {
		if (getComponents().size() > 0)
			return false;

		return true;
	}

	public boolean isFixed() {
		return true;
	}

	@Override
	public int getRequireWidth() {
		return getWidth();
	}

}
